package com.yuqq.token.service.impl;

import com.yuqq.token.domain.LoginUser;
import com.yuqq.token.domain.ResponseResult;
import com.yuqq.token.domain.User;
import com.yuqq.token.service.LoginUserService;
import com.yuqq.token.service.UserDetailsServiceImpl;
import com.yuqq.token.util.JwtUtil;
import com.yuqq.token.util.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Objects;

@Service
public class LoginUserServiceImpl implements LoginUserService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Override
    public ResponseResult login(User user) {
        //创建一个用于 Spring Security 框架内部进行身份认证的“认证请求对象”。
        //它并不是 JWT 令牌，而是 Spring Security 的认证机制中使用的临时凭证。
        //🧠 类比：
        //就像你去银行柜台办理业务时，出示身份证和密码，这个“身份证+密码”就是你的认证信息。
        UsernamePasswordAuthenticationToken authenticationToken = new
                UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        Authentication authenticate =
                authenticationManager.authenticate(authenticationToken);
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("用户名或密码错误");
        }
//使用userid生成token
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getUser().getId().toString();
        String jwt = JwtUtil.createJWT(userId);
//authenticate存入redis
        redisCache.setCacheObject("login:" + userId, loginUser);
//        System.out.println(String.valueOf(redisCache.getCacheObject("login:" + userId)));
//把token响应给前端
        HashMap<String, String> map = new HashMap<>();
        map.put("token", jwt);
        return new ResponseResult(200, "登陆成功", map);
    }

    //删除redis与SecurityContextHolder的用户信息
    @Override
    public ResponseResult logout() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long userid = loginUser.getUser().getId();
        redisCache.deleteObject("login:" + userid);
        return new ResponseResult(200, "退出成功");
    }
}
